<template>
  <div class="node-add">
    <el-form
      :model="nodeData"
      ref="nodeForm"
      :rules="rules"
      hide-required-asterisk
    >
      <el-form-item label="节点名称：" prop="name" class="node-form">
        <el-input
          maxlength="50"
          show-word-limit
          v-model.trim="nodeData.name"
          :readonly="currentType === 'detail'"
          class="default-name"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        label="父级节点："
        class="node-form"
        v-show="currentType === 'detail'"
      >
        <div class="parent-box">
          <el-input
            v-model.trim="parentName"
            readonly="true"
            class="default-name"
          ></el-input>
        </div>
      </el-form-item>
      <el-form-item
        label="父级节点："
        prop="parentIds"
        class="node-form"
        v-show="currentType === 'edit'"
      >
        <div class="parent-box">
          <el-cascader
            ref="refSubCat"
            v-model="nodeData.parentIds"
            :options="parentList"
            @change="handleChange"
            :filter-method="searchParent"
            :show-all-levels="false"
            :props="{ checkStrictly: true }"
            accept=""
            filterable
            clearable
          >
          </el-cascader>
        </div>
      </el-form-item>
    </el-form>
    <div class="upload-img">
      <div class="title">缩略图:</div>
      <el-image
        v-if="currentType === 'detail'"
        style="width: 100px; height: 100px"
        :src="imgUrl"
        fit="fill"
      >
      </el-image>
      <div v-else>
        <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :http-request="uploadImage"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="imgUrl"
            style="width: 100px; height: 100px"
            :src="imgUrl"
            class="avatar"
            fit="fill"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          <!-- <el-button size="small" type="primary" class="reupload">重新上传</el-button> -->
        </el-upload>
      </div>
    </div>
    <div class="property-box">
      <div class="property-header">
        <span class="title">属性信息:</span>
        <el-button
          v-if="currentType !== 'detail'"
          @click="openDialog"
          type="primary"
          >新增</el-button
        >
      </div>
      <div v-if="tableList.length == 0">
        暂无属性信息，点击新增可添加节点属性信息
      </div>
      <el-table v-else :data="tableList" @row-contextmenu="tableClick" border>
        <el-table-column label="序号" width="50" align="center" fixed="left">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="propertyName"
          label="属性名"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="propertyType"
          label="属性值类型"
          align="center"
        ></el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          width="100"
          v-if="currentType !== 'detail'"
        >
          <template slot-scope="scope">
            <el-link
              :underline="false"
              @click="needDelScope(scope.row)"
              v-show="currentType !== 'detail'"
              type="primary"
              v-popover:popover
              >删除</el-link
            >
          </template>

          <!-- <el-button
                    type="primary"
                    class="ontology-delete"
                    @click.native.prevent="deleteProperty(scope.row)"
                    >删除</el-button> -->
        </el-table-column>
        <!-- <el-table-column
                    prop="propertyBind"
                    label="约束配置"
                    align="center"
                ></el-table-column> -->
      </el-table>
    </div>
    <div class="submit-btn">
      <div class="submit-btn-item" v-if="currentType === 'detail'">
        <i class="iconfont iconedit"></i>
        <el-button type="text" @click="changePageStatus('edit')"
          >编辑</el-button
        >
      </div>
      <div class="submit-btn-item" v-else>
        <i class="iconfont iconsave"></i>
        <el-button type="text" @click="changePageStatus('detail')"
          >保存</el-button
        >
      </div>
    </div>
    <el-dialog
      title="新增属性"
      :visible.sync="dialogFormVisible"
      @close="afterDialogClose"
    >
      <el-form
        :model="property"
        :rules="propertyRules"
        ref="dialogForm"
        label-position="right"
        label-width="120px"
      >
        <el-form-item label="属性名:" prop="propertyName" class="dialog-inline">
          <el-input v-model.trim="property.propertyName"></el-input>
        </el-form-item>
        <el-form-item
          label="属性值类型:"
          prop="propertyType"
          class="dialog-inline"
        >
          <el-input type="input" v-model.trim="property.propertyType">
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="约束配置:" prop="bind" class="dialog-inline">
                    <el-input type="input" v-model.trim="property.bind"></el-input>
                </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialogForm">取 消</el-button>
        <el-button type="primary" @click="submitDialogForm" :loading="loading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- <el-popover
            ref="popover"
            placement="top"
            width="160"
            v-model="popoverVisible"
            trigger="click">
            <p>确定删除吗？</p>
            <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="popoverVisible = false">取消</el-button>
                <el-button type="primary" size="mini" @click="confirmDelProperty">确定</el-button>
            </div>
            
            <el-button slot="reference">删除</el-button>
        </el-popover>  -->
  </div>
</template>
<script>
import { deepClone } from "@/plugins/utils";
export default {
  name: "EditNode",
  props: {
    type: {
      type: String,
      default: "detail",
    },
    ontologyAllId: {
      type: Number,
      require: true,
    },
    ontologyAllName: {
      type: String,
      require: true,
    },
  },
  data: () => {
    return {
      nodeData: {
        name: "", // 当前节点name
        // parentName:'', // 父节点name
        parentIds: null, // 祖先节点ids
      },
      parentName: "",
      imgUrl: null, // 缩略图url
      currentType: "edit", // 当前状态
      selfProperty: [], // 自己的属性
      parentProperty: [], // 父节点的属性
      tableList: [], // 包含所有的属性
      parentList: [], // 父节点列表
      dialogFormVisible: false, // 属性dialog
      popoverVisible: false, // 属性删除提示
      property: {
        // 属性
        propertyName: null, // 属性值名
        propertyType: null, // 属性值类型
      },
      propertyRules: {
        // 属性表单规则
        propertyName: [
          {
            required: true,
            message: "请输入属性名",
            trigger: "blur",
          },
        ],
        propertyType: [
          {
            required: true,
            message: "请输入属性值类型",
            trigger: "blur",
          },
        ],
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入节点名称",
            trigger: "blur",
          },
        ],
        parentIds: [
          {
            validator: (rule, value, callback) => {
              if (!value || !value.length) {
                callback(new Error("请选择父级节点"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
      },
      loading: false,
      propertyTypes: [
        {
          label: "数值",
          value: "number",
        },
        {
          label: "日期",
          value: "date",
        },
        {
          label: "日期时间",
          value: "time",
        },
        {
          label: "文本型",
          value: "text",
        },
      ],
      propertyTypesSub: {
        number: [
          "个",
          "厘米",
          "米",
          "千米",
          "平方米",
          "公顷",
          "平方千米",
          "立方米",
          "克",
          "千克",
          "吨",
        ],
        date: ["年", "月", "天"],
        time: ["秒", "分", "时"],
      },
      propertyBind: [
        {
          value: "unbind",
          label: "无约束",
        },
        {
          value: "range",
          label: "范围值",
        },
        {
          value: "enum",
          label: "枚举值",
        },
      ],
      neo4jID: null, // 当前节点的
    };
  },
  created() {
    this.getAllParentNodes();
  },
  methods: {
    // 获取节点详情
    getNodeDetails() {
      let params = {
        id: this.nodeId,
      };
      this.$axios
        .post(this.$api.ontologyModel.getNodeDetail, params)
        .then((res) => {
          let data = res.data.data;
          this.nodeData.name = data.name;
          this.parentName = data.parentName;
          this.nodeData.parentIds = data.parentIds;
          this.imgUrl = data.imgUrl;
          this.tableList = data.property.map((item, index) => {
            item.id = index + 1;
            return item;
          });
          // console.log('tablist',this.selfProperty)
          console.log("data", data);
        });
    },
    // 新增属性
    openDialog() {
      // this.$refs.dialogForm.resetFields();
      this.dialogFormVisible = true;
    },
    // 关闭
    afterDialogClose() {
      this.dialogFormVisible = false;
      this.$refs.dialogForm.resetFields();
    },
    // 切换编辑状态
    changePageStatus(type) {
      console.log("property.propertyType", this.property.propertyType);
      console.log("type", type);
      if (type === "detail") {
        this.$refs.nodeForm.validate((valid) => {
          if (valid) {
            this.saveNode().then((res) => {
              if (res) {
                this.currentType = type;
                this.getNodeDetails();
              }
            });
          } else {
            return false;
          }
        });
      } else {
        this.currentType = type;
      }
    },
    // 获取父节点列表
    getAllParentNodes() {
      console.log("aaaaa");
      let params = {
        ontologyAllId: this.ontologyAllId,
      };
      return this.$axios
        .post(this.$api.ontologyModel.getParentNodes, params)
        .then((res) => {
          let data = res.data.data;
          console.log("allParentList", data);
          this.parentList = data;
        });
    },
    // 查询父类节点
    searchParent(node, keyword) {
      console.log("searchParent", node, keyword);
      if (
        !!~node.text.indexOf(keyword) ||
        !!~node.text.toUpperCase().indexOf(keyword.toUpperCase())
      ) {
        return true;
      }
    },
    tableClick(row, column, event) {
      // console.log('click',row)
    },
    // 删除属性
    deleteProperty(row) {
      let id = row.id;
      console.log("del row", row);
      let delIndex = this.tableList.findIndex((item, index) => {
        return item.id === id;
      });
      if (delIndex > -1) {
        this.tableList.splice(delIndex, 1);
      }

      console.log("delIndex", delIndex);
      console.log("tableList", this.tableList);
    },
    // 获取最新的父节点
    handleChange(e) {
      console.log("change", this.nodeData.parentIds);
      if (this.nodeData.parentIds && this.nodeData.parentIds.length) {
        this.getParentProperty();
      }
      // let labels = this.$refs["refSubCat"].getCheckedNodes()[0].pathLabels;
    },
    // 校验图片格式
    beforeAvatarUpload(file) {
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      // 判定是否是png,jpg,jpeg类型文件
    },
    //上传图片
    uploadImage(fileObj) {
      console.log("file", file);
      let file = fileObj.file;
      this.$fileHttp
        .uploadFile(this.$api.ontologyModel.uploadImg, {
          file,
        })
        .then((res) => {
          let data = res.data.data;
          this.imgUrl = data;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 图上传成功后回调
    handleAvatarSuccess() {
      console.log("upload ok");
    },
    // 新增属性
    submitDialogForm() {
      console.log("submit");
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false;

          this.tableList.push(deepClone(this.property));
          return true;
        } else {
          return false;
        }
      });
    },
    cancelDelProperty() {
      console.log("close");
      this.popoverVisible = false;
    },
    // 确定删除属性
    confirmDelProperty() {
      this.popoverVisible = false;
      // this.deleteProperty(row);
    },
    resetDialogForm() {
      this.dialogFormVisible = false;
    },
    needDelScope(row) {
      this.deleteProperty(row);
      console.log(row);
      // this.popoverVisible = true;
    },
    // 获取父节点的属性
    getParentProperty() {
      let id = this.nodeData.parentIds[this.nodeData.parentIds.length - 1];
      let params = {
        id,
      };
      this.$axios
        .post(this.$api.ontologyModel.getParentProperty, params)
        .then((res) => {
          let data = res.data.data;
          this.tableList = data;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 保存当前节点
    saveNode() {
      let { name, parentIds } = this.nodeData;
      let property = this.tableList.map((item) => {
        let { propertyName, propertyType } = item;
        return {
          propertyName,
          propertyType,
        };
      });
      let params = {
        ontologyAllId: this.ontologyAllId,
        ontologyAllName: this.ontologyAllName,
        ontologyName: name,
        parentId: parentIds.pop(),
        imgUrl: this.imgUrl,
        property,
      };
      console.log("add params", params);
      return this.$axios
        .post(this.$api.ontologyModel.saveNode, params)
        .then((res) => {
          let code = res.data.code;
          let message = res.data.message;
          if (code !== 200) {
            this.$message.warning(message);
            return false;
          } else {
            let data = res.data.data;
            this.neo4jID = data;
            return true;
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.node-add {
  position: relative;
  overflow-y: scroll !important;

  .node-form {
    /deep/ .el-form-item__error {
      margin-left: 85px;
    }

    text-align: left;

    .default-name {
      width: 200px;
    }

    .parent-box {
      .parent-box-input {
        position: relative;
      }

      .hide-select {
        position: absolute;
        top: 0;
        left: 82px;
        z-index: -1;
      }
    }
  }

  .upload-img {
    height: 150px;
    text-align: left;
    position: relative;

    .title {
      margin-bottom: 10px;
    }

    .reupload {
      position: absolute;
      bottom: 0px;
      left: 120px;
    }

    /deep/ .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      // overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }

    .avatar {
      width: 100px;
      height: 100px;
      display: block;
    }
  }

  .property-box {
    .property-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      height: 50px;
    }
  }

  .submit-btn {
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: absolute;
    right: 0;
    top: 0;

    .submit-btn-item {
      margin-right: 5px;
    }
  }

  /deep/ .el-dialog {
    width: 500px;
    border-radius: 5px;
  }
}
</style>
